<?php
namespace app\api\service;

use think\Exception;
use app\lib\exception\WxEx;
use app\api\model\User;
use think\Cache;
use app\lib\enum\Scope;


/** 
* Document
*/
class UserToken extends Token {

    protected $code ;
    protected $wxAppID;
    protected $wxAppSecret;
    protected $wxLoginUrl;

    public function __construct($code) {
        $this->wxAppID = config('wx.app_id');
        $this->wxAppSecret = config('wx.app_secret');
        $this->code = $code;
        $this->wxLoginUrl = sprintf(
            config('wx.login_url')
            ,$this->wxAppID
            ,$this->wxAppSecret
            ,$this->code
        );
    }

    public function get(){
        // $wxRes = http_get($this->wxLoginUrl);
        // $wxRes = json_decode($wxRes,true);
        // TODO 模拟微信返回，调试使用
        $wxRes = [
            "session_key" => "Ql7F1TLkoOjb+BciCUDb4w==",
            "expires_in" => 7200,
            "openid" => "oC18K0SybpjROybfq7Q_aqwvSl4I"
        ];
        if(empty($wxRes)){
            throw new Exception('换取openID和session_key失败，微信内部异常');
        }else{
            $loginFile = array_key_exists('errcode',$wxRes);
            if($loginFile){
                $this->wxLoginError($wxRes);
            }else{
                return $this->grantToken($wxRes);
            }
        }
    }

    private function wxLoginError($wxRes){
        throw new WxEx($wxRes['errmsg'],$wxRes['errcode']);
    }

    /**
     * 授权生成令牌
     *
     * @param string $wxRes
     * @return string
     */
    private function grantToken($wxRes){
        $openId = $wxRes['openid'];
        $user = User::getByOpenid($openId);
        if(empty($user)){
            $newUser = $this->newUser($openId);
            $uid = $newUser->id;
        }else{
            $uid = $user->id;
        }

        # 生成token 作为缓存的key
        $token = $this->generateToken();
        # 拼接缓存数据
        $cacheValues = $wxRes;
        $cacheValues['uid'] = $uid;
        $cacheValues['scope'] = Scope::User;
        $tokenExp = config('secret.tokenExp');
        $cacheKey = config('secret.tokenPre') . $token;
        # 写入缓存
        $res = Cache::set($cacheKey,$cacheValues,$tokenExp);
        if(! $res) throw Exception('写缓存失败');
        return $token;
    }

    public function newUser($openId){
        $user = User::create(
            ['openid'=>$openId]
        );
        return $user;
    }















}